<!-- 市级 - 核查任务正确率统计 -->
<template>
  <div>
    <div class="header">
      <!-- 核查任务正确率统计 -->
      <div> 核查任务正确率统计(市级) </div>
      <div class="search">
        <span>请选择市区：</span>
        <a-select
          ref="select"
          v-model:value="value1"
          style="width: 120px"
          :options="options"
          @change="handleChange"
        />
        <a-button type="primary" @click="queryFn">查询</a-button>
      </div>
      <div class="table-settings">
        <!-- <ImportSetting :tableData="tableData" :tableColumns="tableColumns" v-if="true" /> -->
        <ImportSetting
          :tableData="tableData"
          :tableColumns="tableColumns1"
          :wscolsList="wscolsList"
          ref="ImporBusinessDom"
          excelName="核查任务表"
          @click="importBusinessFn"
        />
      </div>
    </div>
    <a-table
      :dataSource="tableData"
      :columns="tableColumns"
      :pagination="false"
      bordered
      :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <span>
            <a>
              <Tooltip placement="top">
                <template #title>
                  <span>导出</span>
                </template>
                <ImportOutlined @click="importFn(record)" />
              </Tooltip>
            </a>
          </span>
        </template>
        <template v-if="column.key === 'sample_type'">
          <span>
            <span>
              <a-tag
                :color="
                  record.sample_type === 2
                    ? 'volcano'
                    : record.sample_type === 1
                    ? 'geekblue'
                    : record.sample_type === 0
                    ? 'blue'
                    : 'green'
                "
              >
                {{ record.sample_type_text }}
              </a-tag>
            </span>
          </span>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, toRefs, onMounted } from 'vue';
  import { Tooltip } from 'ant-design-vue';
  import { ImportOutlined } from '@ant-design/icons-vue';
  import ImportSetting from './ImportSetting.vue';
  // import { getCountList, getCountPostList } from '/@/api/demo/system';
  import {
    getInspectWorkList,
    getInspectWorkPostList,
    getInspectWorkPostExcelList,
  } from '/@/api/demo/system';
  import { iTableData, iTableColumns, iExcelTableData, iOptions } from './types/table';
  import { iParams } from './types/params';

  import { useUserStore } from '/@/store/modules/user';

  // 转义地区编码
  import { selectClassFlyDict } from '/@/dict/bj_dict';
  import * as XLSX from 'xlsx';
  interface Data {
    tableData: iTableData[];
    tableColumns: iTableColumns[];
    tableColumns1: iTableColumns[];
    excelTableData: iExcelTableData[];
    exceltableColumns: iTableColumns[];
    id: number | string | null;
    loading: boolean;
    keyWorld: string;
    cityToken: string;
    wscolsList: { wch: number }[];
  }
  // 处理时间的方法
  function formatDate(date: string): string {
    const T = date.substring(date.indexOf('.'), date.length);
    const T1 = date.replace(T, '');
    const T2 = T1.replace('T', ' ');
    return T2;
  }
  let data = reactive<Data>({
    // 表格数据
    tableData: [],
    tableColumns: [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        align: 'center',
        width: 70,
      },
      {
        title: '任务包名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '抽样条数',
        dataIndex: 'sample_count',
        key: 'sample_count',
        width: 100,
        align: 'center',
      },
      // {
      //   title: '初判结果',
      //   dataIndex: 'sample_type_text',
      //   key: 'sample_type_text',
      //   align: 'center',
      // },
      {
        title: '初判结果',
        dataIndex: 'sample_type',
        key: 'sample_type',
        align: 'center',
      },
      {
        title: '抽样区域',
        dataIndex: 'sample_area',
        key: 'sample_area',
        align: 'center',
      },
      {
        title: '抽样时间',
        dataIndex: 'create_on',
        key: 'create_on',
        align: 'center',
        customRender: ({ record }) => formatDate(record.create_on),
      },
      {
        title: '抽样比例',
        dataIndex: 'cybi',
        key: 'cybi',
        align: 'center',
        width: 100,
      },
      {
        title: '任务包指派',
        dataIndex: 'rwbzp',
        key: 'rwbzp',
        align: 'center',
      },
      {
        title: '核查正确数',
        dataIndex: 'hc_zq',
        key: 'hc_zq',
        align: 'center',
      },
      {
        title: '核查错误数',
        dataIndex: 'hc_err',
        key: 'hc_err',
        align: 'center',
      },
      {
        title: '正确率',
        dataIndex: 'hc_acuracy',
        key: 'hc_acuracy',
        align: 'center',
      },
      {
        title: '导出',
        key: 'action',
        align: 'center',
      },
    ],
    tableColumns1: [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        align: 'center',
        width: 70,
      },
      {
        title: '任务包名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '抽样条数',
        dataIndex: 'sample_count',
        key: 'sample_count',
        width: 100,
        align: 'center',
      },
      {
        title: '初判结果',
        dataIndex: 'sample_type',
        key: 'sample_type',
        align: 'center',
      },
      {
        title: '抽样区域',
        dataIndex: 'sample_area',
        key: 'sample_area',
        align: 'center',
      },
      {
        title: '抽样时间',
        dataIndex: 'create_on',
        key: 'create_on',
        align: 'center',
        customRender: ({ record }) => formatDate(record.create_on),
      },
      {
        title: '抽样比例',
        dataIndex: 'cybi',
        key: 'cybi',
        align: 'center',
        width: 100,
      },
      {
        title: '任务包指派',
        dataIndex: 'rwbzp',
        key: 'rwbzp',
        align: 'center',
      },
      {
        title: '核查正确数',
        dataIndex: 'hc_zq',
        key: 'hc_zq',
        align: 'center',
      },
      {
        title: '核查错误数',
        dataIndex: 'hc_err',
        key: 'hc_err',
        align: 'center',
      },
      {
        title: '正确率',
        dataIndex: 'hc_acuracy',
        key: 'hc_acuracy',
        align: 'center',
      },
    ],
    excelTableData: [],
    exceltableColumns: [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        align: 'center',
        width: 100,
      },
      {
        title: '编号',
        dataIndex: 'bh',
        key: 'bh',
        align: 'center',
        width: 100,
      },
      {
        title: '自建房安全排查编号',
        dataIndex: 'yhfwbh',
        key: 'yhfwbh',
        align: 'center',
      },
      {
        title: '普查房屋编号',
        dataIndex: 'fwbh',
        key: 'fwbh',
        align: 'center',
      },
      {
        title: '房屋地址',
        dataIndex: 'address',
        key: 'address',
        align: 'center',
      },
      {
        title: '区县编码',
        dataIndex: 'xzqdm',
        key: 'xzqdm',
        align: 'center',
      },
      {
        title: '区县名称',
        dataIndex: 'xzqdm_text',
        key: 'xzqdm_text',
        align: 'center',
      },
      {
        title: '街道编码',
        dataIndex: 'town',
        key: 'town',
        align: 'center',
      },
      {
        title: '街道名称',
        dataIndex: 'town_text',
        key: 'town_text',
        align: 'center',
      },
      {
        title: '村（社区）编码',
        dataIndex: 'village',
        key: 'village',
        align: 'center',
      },
      {
        title: '组',
        dataIndex: 'zu_qg',
        key: 'zu_qg',
        align: 'center',
      },
      {
        title: '路（街、巷）',
        dataIndex: 'lu_qg',
        key: 'lu_qg',
        align: 'center',
      },
      {
        title: '号',
        dataIndex: 'hao_qg',
        key: 'hao_qg',
        align: 'center',
      },
      {
        title: '建筑地址',
        dataIndex: 'address',
        key: 'address',
        align: 'center',
      },
      {
        title: '户主姓名',
        dataIndex: 'hzxm',
        key: 'hzxm',
        align: 'center',
      },
      {
        title: '初步判定',
        dataIndex: 'aqyhcp_text',
        key: 'aqyhcp_text',
        align: 'center',
      },
      {
        title: '区县核查结果',
        dataIndex: 'result_text',
        key: 'result_text',
        align: 'center',
      },
      {
        title: '市级核查结果',
        dataIndex: 'city_result_text',
        key: 'city_result_text',
        align: 'center',
      },
    ],
    id: null,
    loading: true,
    keyWorld: '',
    cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索框
    wscolsList: [{ wch: 20 }, { wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }],
  });
  // 表格的 ref Dom名称
  const ImporBusinessDom = ref<any>(null);
  const value1 = ref('北京市'); // 存储select 的 默认值
  const options = ref<iOptions[]>([
    {
      value: '110000',
      label: '北京市',
    },
    {
      value: '110101',
      label: '东城区',
    },
    {
      value: '110102',
      label: '西城区',
    },
    {
      value: '110105',
      label: '朝阳区',
    },
    {
      value: '110106',
      label: '丰台区',
    },
    {
      value: '110107',
      label: '石景山区',
    },
    {
      value: '110108',
      label: '海淀区',
    },
    {
      value: '110109',
      label: '门头沟区',
    },

    {
      value: '110111',
      label: '房山区',
    },
    {
      value: '110112',
      label: '通州区',
    },
    {
      value: '110113',
      label: '顺义区',
    },
    {
      value: '110114',
      label: '昌平区',
    },

    {
      value: '110115',
      label: '大兴区',
    },
    {
      value: '110116',
      label: '怀柔区',
    },
    {
      value: '110117',
      label: '平谷区',
    },
    {
      value: '110118',
      label: '密云区',
    },

    {
      value: '110119',
      label: '延庆区',
    },
    {
      value: '110171',
      label: '北京市经济技术开发区',
    },
  ]);
  let {
    tableData,
    tableColumns,
    tableColumns1,
    loading,
    excelTableData,
    exceltableColumns,
    keyWorld,
    wscolsList,
  } = toRefs(data);
  function getAreaToken() {
    const { getUserInfo } = useUserStore();
    // data.cityToken = getUserInfo.district.id;
    data.cityToken = (getUserInfo.district && getUserInfo.district.id) || '110000';
    // 保存select 中的值
    data.id = (getUserInfo.district && getUserInfo.district.id) || '110000';
    // 根据缓冲中的 市、区县代码 获取 市、区县名称
    let name: string = selectClassFlyDict(data.id);
    // 把 市、区县名称 赋值给 下拉框 进行请求
    value1.value = name;
  }
  // select 选中 回调
  function handleChange(value: string) {
    data.keyWorld = value;
    // console.log('@data.keyWorld', data.keyWorld);
  }
  // 查询方法
  function queryFn() {
    data.id = keyWorld.value === '' ? data.cityToken : keyWorld.value;
    // data.id = data.keyWorld;
    // console.log('data.id', data.id);
    getData();
  }
  async function getData() {
    let params: iParams;
    let res: any;
    let tableData: any[] = [];
    if (data.id === '110000') {
      // 北京市 和 所有区的数据
      params = {
        id: `zj_tj_citycx_${data.id}_fzz`,
      };
      data.loading = true;
      res = await getInspectWorkList(params);
    } else {
      // 北京市 下面 区县的 数据
      params = {
        id: `zj_tj_citycx2_fzz`,
        xzqdm: `${data.id}`,
      };
      data.loading = true;
      res = await getInspectWorkPostList(params);
    }
    if (res && res.length > 0) {
      tableData = res.map((item: any, index: number) => {
        let sample_area = '';
        let hc_jd = '';
        let hc_accuracy = '';
        let hc_ratio = '';
        let sample_type_text = '';
        let cybi = '';
        item.index = index + 1;
        // 处理 抽样区域
        const area = JSON.parse(item.sample_area_code);
        if (area !== null) {
          sample_area = area[0].RegionName;
        }
        // 处理 核查进度
        hc_jd = item.hc_jd === null ? '' : `${item.hc_jd}%`;

        // 处理 正确率
        hc_accuracy = item.hc_acuracy === null ? '' : `${item.hc_acuracy}%`;

        // 处理 抽样比例
        hc_ratio = item.hc_ratio === null ? '' : `${item.hc_ratio}%`;
        // 处理 初判结果
        switch (item.sample_type) {
          case 2:
            sample_type_text = '严重安全隐患';
            break;
          case 1:
            sample_type_text = '一般隐患';
            break;
          case 0:
            sample_type_text = '无隐患';
            break;
          default:
            sample_type_text = '全部';
        }
        // 处理核查正确率
        cybi = item.cybi === null ? '' : `${item.cybi}%`;
        return {
          ...item,
          sample_area,
          hc_jd,
          hc_accuracy,
          hc_ratio,
          sample_type_text,
          cybi,
        };
      });
    }
    data.loading = false;
    data.tableData = tableData;
  }

  // 导出
  function importFn(record) {
    // console.log('@record', record);
    const { id } = record;
    const params: iParams = {
      id: `zj_tj_citycx_mx_fzz`,
      taskid: `${id}`,
    };
    getInspectWorkPostExcelList(params).then((res: any) => {
      res.forEach((item: any) => {
        const { xzqdm, town, aqyhcp, result, city_result } = item;

        item.xzqdm_text = selectClassFlyDict(xzqdm);
        item.town_text = selectClassFlyDict(town);

        switch (aqyhcp) {
          case '1':
            item.aqyhcp_text = '存在严重安全隐患';
            break;
          case '2':
            item.aqyhcp_text = '未发现安全隐患';
            break;
          case '3':
            item.aqyhcp_text = '存在一般安全隐患';
            break;
          default:
            break;
        }

        switch (result) {
          case 0:
            item.result_text = '不正确';
            break;
          case 1:
            item.result_text = '正确';
            break;
          case null:
            item.result_text = '';
            break;
          default:
            break;
        }

        item.city_result_text =
          city_result === null ? '未核查' : city_result === 0 ? '不正确' : '正确';
      });

      data.excelTableData = [...res];
      // 导出表格
      if (data.excelTableData) {
        exportTable(exceltableColumns.value, excelTableData.value);
      }
    });
  }
  // 当前整体表格页面导出
  function importBusinessFn() {
    // 去掉 导出列 ，然后导出表格
    // data.tableColumns.splice(data.tableColumns.length - 1, 1);
    if (ImporBusinessDom.value) {
      ImporBusinessDom.value.importFn();
    }
  }
  function exportTable(Columns, TableData) {
    let content: any[] = TableData; //拿到后端返回的数据
    let Header: any[] = Columns;
    createTable(Header, content); //调用下面的方法来制作表格
  }
  // 创建表格
  function createTable(Header, content) {
    let table = document.createElement('table'); //创建table
    let thead = document.createElement('thead'); //thead
    let tbody = document.createElement('tbody'); //thead
    let tr = document.createElement('tr'); //创建tr
    table.appendChild(thead);
    table.appendChild(tbody);
    thead.appendChild(tr);
    // 创建表头
    Header.forEach((item: any) => {
      let th = document.createElement('th');
      th.innerHTML = item.title;
      tr.appendChild(th);
    });
    // 添加内容
    content.forEach((item: any) => {
      let tr = document.createElement('tr'); //创建tr
      tbody.appendChild(tr);
      Header.forEach((item2: any) => {
        let td = document.createElement('td');
        let itemString: any = Object.entries(item);
        for (let item3 of itemString) {
          if (item2.key === item3[0]) {
            td.innerHTML = item3[1];
          }
        }
        tr.appendChild(td);
      });
    });
    //导出
    // 1.table 转 sheet 页
    let worksheet: any = XLSX.utils.table_to_sheet(table);
    // console.log('@worksheet', worksheet);

    // 2.新建工作簿
    let workbook: any = XLSX.utils.book_new();
    // console.log('@workbook', workbook);
    // 将表格内容变成文本
    let xlsxParam = { raw: true }; // 将表格数据设置为文本格式
    workbook = XLSX.utils.table_to_book(table, xlsxParam);

    // 3.设置列宽
    let wscols: any[] = [
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 50 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
    ];
    // workbook.SheetNames[0]获取到到是文件里的到第一个表格
    worksheet['!cols'] = wscols;
    let wsrows: any[] = [{ hpx: 20 }]; // 每行固定高度px
    for (let i = 0; i <= 5; i++) {
      wsrows.push({ hpx: 20 });
    }
    worksheet['!rows'] = wsrows;
    XLSX.utils.book_append_sheet(workbook, worksheet, 'sheet');
    try {
      // 4.输出表格
      XLSX.writeFile(workbook, `自建房核查统计表.xlsx`);
    } catch (e) {
      console.log(e, workbook);
    }
  }
  onMounted(() => {
    getAreaToken();
    getData();
  });
</script>

<style lang="less">
  .header {
    width: 100%;
    height: 40px;
    display: flex;
    // border: 1px solid red;
    line-height: 40px;
    justify-content: space-between;
    .search {
      // border: 1px solid green;
      align-self: flex-end;
      flex: auto;
      margin-left: 15px;
    }
    .table-settings {
      & > * {
        margin-right: 12px;
      }

      svg {
        width: 1.3em;
        height: 1.3em;
      }
    }
  }
</style>
